package com.polaris.live.ui.vip.fragment

import android.os.Build
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.polaris.live.R
import com.polaris.live.adapter.vip.VipIdentityAdapter
import com.polaris.live.adapter.vip.VipPrivilegesAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnScrollChangeListenerCompat
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.resp.UserResp
import com.polaris.live.common.util.DateUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.FragmentVipCenterOwnBinding
import com.polaris.live.dialog.VipBuyDialog
import com.polaris.live.dialog.VipBuySuccessfulDialog
import com.polaris.live.dialog.VipGiveSuccessfulDialog
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.VipPrivilegePopup
import com.polaris.live.resp.back_resp.UserVipIdentity
import com.polaris.live.resp.back_resp.UserVipLevel
import com.polaris.live.resp.back_resp.UserVipPrivilege
import com.polaris.live.translation.R.string
import com.polaris.live.utils.VipStyle
import com.polaris.live.utils.VipStyleBean
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.playAsync2
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.VipCenterOwnViewModel
import com.polaris.live.widget.avatar.FrameImageUtils
import org.greenrobot.eventbus.EventBus

/**
 * VipCenterOwnFragment
 *
 * @author Created by 天晴 on 2024/12/10 10:40
 * @since 1.0.0
 **/
class VipCenterOwnFragment : BaseVbFragment<VipCenterOwnViewModel, FragmentVipCenterOwnBinding>() {

    val mLevel: Long by lazy { arguments?.getLong("level") ?: 0L }

    private val mData: UserVipLevel? by lazy {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getParcelable("data", UserVipLevel::class.java)
        } else {
            arguments?.getParcelable("data")
        }
    }

    private val mVipStyleBean: VipStyleBean by lazy {
        VipStyle.getVipStyle(mLevel)
    }

    private var mUserVipLevels: UserVipLevel? = null

    private val mIdentityAdapter by lazy { VipIdentityAdapter(mLevel) }
    private val mIdentityAdapter2 by lazy { VipIdentityAdapter(mLevel) }

    private val mVipPrivilegesAdapter by lazy { VipPrivilegesAdapter(mLevel) }

    private var mMedalPagInit = false

    override fun initView(savedInstanceState: Bundle?) {
        mVipStyleBean.apply {
            mBinding.root.setBackgroundColor(ColorUtils.getColor(vipMainBgColor))
            mBinding.titleImg.setImageResource(vipTitle)
            mBinding.medalImg.setImageResource(vipMedalTitle)
            mBinding.ownCl.setBackgroundResource(vipOwnInfoBg)
            mBinding.dressingTv.setBackgroundResource(vipBuyBg)
            mBinding.privilegesLl.setBackgroundResource(vipMainPrivilegesColor)
            mBinding.bottomBuyLl.setBackgroundResource(vipBuyBottomBg)
            mBinding.buyBg.setBackgroundResource(vipBuyBg)
            mBinding.experienceCl.setBackgroundResource(vipExperienceBg)
            mBinding.experienceCardImg.setImageResource(vipExperienceCard)
            mBinding.trialMedalImg.setImageResource(vipExperienceCard)
            mBinding.titleBgView.setBackgroundColor(ColorUtils.getColor(vipMainBgColor))
        }

        val bottomView = mBinding.bottom
        val lp = bottomView.layoutParams as ViewGroup.LayoutParams
        lp.height = NavigationBarUtils.getNavigationBarHeight(requireContext())
        bottomView.layoutParams = lp
        mBinding.identificationRecycler.apply {
            layoutManager = GridLayoutManager(requireContext(), 3)
            adapter = mIdentityAdapter
            itemAnimator = null
        }
        mBinding.outfitRecycler.apply {
            layoutManager = GridLayoutManager(requireContext(), 3)
            adapter = mIdentityAdapter2
            itemAnimator = null
        }
        mBinding.privilegesRecycler.apply {
            layoutManager = GridLayoutManager(requireContext(), 3)
            adapter = mVipPrivilegesAdapter
            itemAnimator = null
        }
        val reserveIdentityList = arrayListOf<UserVipIdentity>() //占位数据
        val reservePrivilegeList = arrayListOf<UserVipPrivilege>() //占位数据
        repeat(6) {
            reserveIdentityList.add(
                UserVipIdentity(
                    null,
                    null,
                    null,
                    "-1",
                    "",
                    null,
                    "",
                    "",
                    null,
                    null
                )
            )
            reservePrivilegeList.add(
                UserVipPrivilege(
                    false,
                    null,
                    "-1",
                    "",
                    "",
                    "",
                    null,
                    null
                )
            )
        }
        mIdentityAdapter.setList(reserveIdentityList)
        mIdentityAdapter2.setList(reserveIdentityList)
        mVipPrivilegesAdapter.setList(reservePrivilegeList)

        initListener()
        initObserver()
        mData?.let {
            setData(it)
        }
    }

    fun upDataUser() {
        mData?.let {
            setData(it)
        }
    }

    fun setData(userVipLevels: UserVipLevel) {
        this.mUserVipLevels = userVipLevels
        when (userVipLevels.bizType) {
            0L -> { //没有开会员
                mBinding.medalImg.alpha = 0.5f
                mBinding.medalPag.visibility = View.GONE
                mBinding.experienceCl.visibility = View.GONE
                mBinding.ownDataCl.visibility = View.GONE
                mBinding.bottomBuyLl.visibility = View.GONE
            }

            1L -> { //续费期内
                setUiRenew(userVipLevels)
            }

            2L -> {
                setUiOfficiallyOnly(userVipLevels)
            }

            3L -> {
                setUiTrialOnly(userVipLevels)
            }

            4L -> {
                setUiOfficiallyAndTrial(userVipLevels)
            }
        }

    }

    /**
     * 续费
     */
    private fun setUiRenew(userVipLevels: UserVipLevel) {
        val user = UserManager.getUser()
        mBinding.experienceCl.visibility = View.GONE
        mBinding.medalImg.visibility = View.VISIBLE
        mBinding.trialMedalImg.visibility = View.GONE
        mBinding.medalPag.visibility = View.GONE

        Glide.with(requireContext())
            .load(ImageUtils.imgPath(userVipLevels.fallbackMedalUrl))
            .into(mBinding.medalImg)

        mBinding.ownDataCl.visibility = View.VISIBLE
        mBinding.bottomBuyLl.visibility = View.VISIBLE
        mBinding.priceTv.text = "${userVipLevels.renewalPrice}"
        mBinding.dayTv.text = "/${userVipLevels.priceDays}days"
        mBinding.givePriceTv.text = "${userVipLevels.price}"
        mBinding.giveDayTv.text = "/${userVipLevels.priceDays}days"
        mIdentityAdapter.setList(userVipLevels.identities.filter { it.decorationType == null })
        mIdentityAdapter2.setList(userVipLevels.identities.filter { it.decorationType != null })
        mVipPrivilegesAdapter.setList(userVipLevels.privileges.filter { it.active })



        mBinding.timeTv.setTextColor(ColorUtils.getColor(R.color.ffffff_50))
        val renewalDays = "${userVipLevels.renewalDays}"
        val msg = StringUtils.getString(
            string.expired_days,
            renewalDays
        )
        val index = msg.indexOf(renewalDays)
        val spannableString = SpannableString(msg)
        if (index != -1) {
            val color = ContextCompat.getColor(requireContext(), R.color.color_fffb00)
            spannableString.setSpan(
                ForegroundColorSpan(color),
                index,
                index + renewalDays.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        mBinding.timeTv.text = spannableString


        mBinding.timeDayTv.setTextColor(ColorUtils.getColor(R.color.color_fffb00))
        mBinding.timeDayTv.text = StringUtils.getString(string.become_due)


        mBinding.periodValidityTv.text = StringUtils.getString(
            string.remaining_validity_period_days,
            userVipLevels.renewalDays
        )

        mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(user.decoration?.avatarFrame))
        mBinding.avatar.setImageUrl(user.avatar, user.userId)
        mBinding.nameTv.text = user.nickname
        mBinding.nameTv.setNicknameColor(
            user.decoration?.nicknameColor,
            com.polaris.live.common.R.color.white
        )
        mBinding.idTv.setId(user)
        mBinding.vipView.setVipLevel((user.profile?.vipLevel))
        mBinding.levelView.setRichsLevel(user.account?.richs ?: 0)

    }

    /**
     * 仅试用
     */
    private fun setUiTrialOnly(userVipLevels: UserVipLevel) {
        val user = UserManager.getUser()
        mBinding.experienceCl.visibility = View.GONE
        mBinding.trialMedalImg.visibility = View.VISIBLE
        mBinding.medalImg.visibility = View.GONE
        mBinding.medalPag.visibility = View.GONE


        mBinding.ownDataCl.visibility = View.VISIBLE
        mBinding.bottomBuyLl.visibility = View.VISIBLE

        mBinding.priceTv.text = "${userVipLevels.renewalPrice}"
        mBinding.dayTv.text = "/${userVipLevels.priceDays}days"
        mBinding.givePriceTv.text = "${userVipLevels.price}"
        mBinding.giveDayTv.text = "/${userVipLevels.priceDays}days"
        mIdentityAdapter.setList(userVipLevels.identities.filter { it.decorationType == null })
        mIdentityAdapter2.setList(userVipLevels.identities.filter { it.decorationType != null })
        mVipPrivilegesAdapter.setList(userVipLevels.privileges.filter { it.active })

        mBinding.timeTv.setTextColor(ColorUtils.getColor(R.color.white))
        mBinding.timeTv.text = userVipLevels.expireTime?.let { time ->
            val timeStr = DateUtils.convertTimestampToString(time.toLong())
            StringUtils.getString(string.validity_period_days, timeStr)
        } ?: ""
        val days = userVipLevels.trialDays
        if (days == 0L) { //不足一天
            mBinding.timeDayTv.text = StringUtils.getString(string.vip_has_1_days)
        } else {
            val sDay = "$days"
            val msg = StringUtils.getString(string.vip_has_days_left, days)
            val index = msg.indexOf(sDay)
            val spannableString = SpannableString(msg)
            if (index > 0) {
                val color = ContextCompat.getColor(requireContext(), R.color.color_fffb00)
                spannableString.setSpan(
                    ForegroundColorSpan(color),
                    index,
                    index + sDay.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
            mBinding.timeDayTv.text = spannableString
        }
        mBinding.medalImg.alpha = 1f

        mBinding.periodValidityTv.text = StringUtils.getString(
            string.remaining_validity_period_days,
            days
        )
        setUserInfo(user)
    }

    /**
     * 仅正式
     */
    private fun setUiOfficiallyOnly(userVipLevels: UserVipLevel) {
        val user = UserManager.getUser()
        mBinding.experienceCl.visibility = View.GONE
        mBinding.medalImg.visibility = View.VISIBLE
        mBinding.medalImg.setImageResource(mVipStyleBean.vipMedalTitle)
        mBinding.trialMedalImg.visibility = View.GONE
        mBinding.medalPag.visibility = View.VISIBLE
        mBinding.medalPag.playAsync2(lifecycleScope, userVipLevels.displayEffectUrl, playCallBack = {
            mBinding.medalImg.visibility = View.GONE
            mMedalPagInit = true
        })


        mBinding.ownDataCl.visibility = View.VISIBLE
        mBinding.bottomBuyLl.visibility = View.VISIBLE

        mBinding.priceTv.text = "${userVipLevels.renewalPrice}"
        mBinding.dayTv.text = "/${userVipLevels.priceDays}days"
        mBinding.givePriceTv.text = "${userVipLevels.price}"
        mBinding.giveDayTv.text = "/${userVipLevels.priceDays}days"
        mIdentityAdapter.setList(userVipLevels.identities.filter { it.decorationType == null })
        mIdentityAdapter2.setList(userVipLevels.identities.filter { it.decorationType != null })
        mVipPrivilegesAdapter.setList(userVipLevels.privileges.filter { it.active })

        mBinding.timeTv.setTextColor(ColorUtils.getColor(R.color.white))
        mBinding.timeTv.text = userVipLevels.expireTime?.let { time ->
            val timeStr = DateUtils.convertTimestampToString(time.toLong())
            StringUtils.getString(string.validity_period_days, timeStr)
        } ?: ""

        val days = userVipLevels.days
        if (days == 0L) { //不足一天
            mBinding.timeDayTv.text = StringUtils.getString(string.vip_has_1_days)
        } else {
            val sDay = "$days"
            val msg = StringUtils.getString(string.vip_has_days_left, days)
            val index = msg.indexOf(sDay)
            val spannableString = SpannableString(msg)
            if (index > 0) {
                val color = ContextCompat.getColor(requireContext(), R.color.color_fffb00)
                spannableString.setSpan(
                    ForegroundColorSpan(color),
                    index,
                    index + sDay.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
            mBinding.timeDayTv.text = spannableString
        }

        mBinding.medalImg.alpha = 1f

        mBinding.periodValidityTv.text = StringUtils.getString(
            string.remaining_validity_period_days,
            days
        )

        setUserInfo(user)

    }

    /**
     * 有正式和试用
     */
    private fun setUiOfficiallyAndTrial(userVipLevels: UserVipLevel) {
        val user = UserManager.getUser()
        mBinding.experienceCl.visibility = View.VISIBLE
        mBinding.experienceDayTv.text =
            StringUtils.getString(string.vip_experience_card_days, userVipLevels.trialDays)
        mBinding.medalImg.setImageResource(mVipStyleBean.vipMedalTitle)
        mBinding.medalImg.visibility = View.VISIBLE
        mBinding.trialMedalImg.visibility = View.GONE
        mBinding.medalPag.visibility = View.VISIBLE

        mBinding.medalPag.playAsync2(lifecycleScope, userVipLevels.displayEffectUrl, playCallBack = {
            mBinding.medalImg.visibility = View.GONE
            mMedalPagInit = true
        })


        mBinding.ownDataCl.visibility = View.VISIBLE
        mBinding.bottomBuyLl.visibility = View.VISIBLE

        mBinding.priceTv.text = "${userVipLevels.renewalPrice}"
        mBinding.dayTv.text = "/${userVipLevels.priceDays}days"
        mBinding.givePriceTv.text = "${userVipLevels.price}"
        mBinding.giveDayTv.text = "/${userVipLevels.priceDays}days"
        mIdentityAdapter.setList(userVipLevels.identities.filter { it.decorationType == null })
        mIdentityAdapter2.setList(userVipLevels.identities.filter { it.decorationType != null })
        mVipPrivilegesAdapter.setList(userVipLevels.privileges.filter { it.active })

        mBinding.timeTv.setTextColor(ColorUtils.getColor(R.color.white))
        mBinding.timeTv.text = userVipLevels.expireTime?.let { time ->
            val timeStr =
                if (userVipLevels.days != 0L && userVipLevels.trialDays != 0L && userVipLevels.renewalDays == 0L) {//有试用和正式  时间显示正式
                    val nt = time.toLong() - userVipLevels.trialDays * 24 * 60 * 60 * 1000
                    DateUtils.convertTimestampToString(nt)
                } else {
                    DateUtils.convertTimestampToString(time.toLong())
                }
            StringUtils.getString(string.validity_period_days, timeStr)
        } ?: ""
        val days = userVipLevels.days
        if (days == 0L) { //不足一天
            mBinding.timeDayTv.text = StringUtils.getString(string.vip_has_1_days)
        } else {
            val sDay = "$days"
            val msg = StringUtils.getString(string.vip_has_days_left, days)
            val index = msg.indexOf(sDay)
            val spannableString = SpannableString(msg)
            if (index > 0) {
                val color = ContextCompat.getColor(requireContext(), R.color.color_fffb00)
                spannableString.setSpan(
                    ForegroundColorSpan(color),
                    index,
                    index + sDay.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
            mBinding.timeDayTv.text = spannableString
        }
        mBinding.medalImg.alpha = 1f

        val day2 = userVipLevels.days + userVipLevels.trialDays
        mBinding.periodValidityTv.text = StringUtils.getString(
            string.remaining_validity_period_days,
            day2
        )

        setUserInfo(user)
    }

    private fun setUserInfo(user: UserResp) {
        mBinding.apply {
            avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(user.decoration?.avatarFrame))
            avatar.setImageUrl(user.avatar, user.userId)
            nameTv.text = user.nickname
            nameTv.setNicknameColor(
                user.decoration?.nicknameColor,
                com.polaris.live.common.R.color.white
            )
            idTv.setId(user)
            vipView.setVipLevel((user.profile?.vipLevel))
            levelView.setRichsLevel(user.account?.richs ?: 0)
        }

    }

    private fun initListener() {
        mBinding.daysSll.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.VIP_DETAIL_ACTIVITY)
                .navigation(requireActivity())
        }
        mBinding.dressingTv.setOnSingleClickListener {
            mUserVipLevels?.let {
                mViewModel.vipInstall(it.level)
            }

        }
        mBinding.buyBtnTv.setOnSingleClickListener {
            mUserVipLevels?.let {
                VipBuyDialog.show(requireContext(), it.level, it.renewalPrice, it.priceDays) {
                    mViewModel.vipBuy(it.level)
                }
            }

        }
        mBinding.trialMedalImg.setOnSingleClickListener {
            ToastGravity.showGravity(StringUtils.getString(string.vip_experience_card_is_welfare))

        }
        mBinding.experienceCardImg.setOnSingleClickListener {
            ToastGravity.showGravity(StringUtils.getString(string.vip_experience_card_is_welfare))

        }
        mIdentityAdapter.setOnItemClickListener { adapter, view, position ->
            mUserVipLevels?.let {
                val data = mIdentityAdapter.getItem(position)
                val index = it.identities.indexOf(data).takeIf { it >= 0 } ?: 0
                VipPrivilegePopup.show(requireContext(), true, index, it) {
                    upData?.invoke()
                }
            }
        }
        mIdentityAdapter2.setOnItemClickListener { adapter, view, position ->
            mUserVipLevels?.let {
                val data = mIdentityAdapter2.getItem(position)
                val index = it.identities.indexOf(data).takeIf { it >= 0 } ?: 0
                VipPrivilegePopup.show(requireContext(), true, index, it) {
                    upData?.invoke()
                }
            }
        }
        mVipPrivilegesAdapter.setOnItemClickListener { adapter, view, position ->
            mUserVipLevels?.let {
                val index = it.identities.size + position
                VipPrivilegePopup.show(requireContext(), true, index, it) {
                    upData?.invoke()
                }
            }
        }
    }

    private fun initObserver() {
        mBinding.nesScrollView.setOnScrollChangeListenerCompat { scrollY ->
            val alpha = (scrollY / 120.autoDp.toFloat()).coerceIn(0f, 1f)
            mBinding.titleBgView.alpha = alpha

        }
        mViewModel.vipBuyLiveData.observe(this) { resultState ->
            parseState(resultState, { req ->
                EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
                upData?.invoke()
                mUserVipLevels?.let { data ->
                    if (req.otherUserId == null) {
                        VipBuySuccessfulDialog.show(requireContext(), req.vipLevel, data.priceDays) {
                        }
                    } else {
                        VipGiveSuccessfulDialog.show(requireContext(), req.vipLevel, data.priceDays)
                    }
                }
            }, {
                ToastGravity.showGravity(it.errorMsg)
                if (it.errCode == CommonConst.ErrorCode.SENDGIFT) {
                    GlobalPopupManager.showRechargePopup(
                        requireContext(),
                        mViewModel,
                        isNeedBottom = true, onRechargeOk = {
                            EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
                        })
                }
            })
        }
        mViewModel.vipInstallLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(StringUtils.getString(string.installed_successfully))
                EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private var upData: (() -> Unit)? = null
    fun upData(back: () -> Unit) {
        this.upData = back

    }

    override fun onResume() {
        super.onResume()
        if (mMedalPagInit) {
            mBinding.medalPag.setCurrentFrame(0)
            if (!mBinding.medalPag.isPlaying) {
                mBinding.medalPag.play()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        if (mMedalPagInit) {
            if (mBinding.medalPag.isPlaying) {
                mBinding.medalPag.pause()
                mBinding.medalPag.setCurrentFrame(0)
            }
        }
    }

}